﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;

namespace CrmWorkflowDependencies.Crm.Extension
{
    public static class IOrganizationServiceExtensions
    {
        public static Entity FindRecord(this IOrganizationService crm, string etn, Guid id)
        {
            return FindMultipleRecords(crm, etn, etn + "id", id, true).FirstOrDefault();
        }

        public static DataCollection<Entity> FindMultipleRecords(this IOrganizationService crm, string etn, string fieldname, object value, bool topOne = true, bool onlyActive = false)
        {
            QueryExpression query = new QueryExpression(etn);
            query.ColumnSet = new ColumnSet(true);
            query.Criteria.AddCondition(fieldname, ConditionOperator.Equal, value);
            query.AddOrder("modifiedon", OrderType.Descending);
            if (topOne) query.PageInfo = new PagingInfo { Count = 1, PageNumber = 1 };
            if (onlyActive && !new[] { "salesorderdetail" }.Contains(etn)) query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
            var ec = crm.RetrieveMultiple(query).Entities;
            return ec;
        }
  }
}
